package taskMgr;

import defaultPackage.Grid;
import defaultPackage.Person;
import defaultPackage.tileType;
import java.awt.*;
public class TaskBuildTile extends Task 
{
	public TaskBuildTile(tileType type,int x,int y) 
	{
		super();
		this.setBuildTile(true);
		this.type=type;
		this.x=x;
		this.y=y;
	}
	tileType type;
	
	public void draw(Graphics g)
	{
		g.setColor(type.getColor());
		g.drawRect(x*10, y*10, 9, 9);
		if (progress > 0)
		{
			g.setColor(type.getColor());
			g.fillRect(x*10, y*10, 9, progress/2);
		}
	}

	public void action(Person p)
	{
		
		if(p.main.grid.tiles[x][y].type == type)
		{
			p.finishCurrentTask();
		}
		p.main.grid.tiles[x][y].setJobHere(true);
		boolean hasPerson = false;
		if (Math.abs(p.getX()-x) <= 1 && Math.abs(p.getY()-y) <= 1 && !(x == p.getX() && y == p.getY()))
		{
			hasPerson = true;
			p.setHasDestination(false);
		}
		if (hasPerson && !p.main.grid.tiles[x][y].hasPerson())
		{
			p.main.grid.tiles[x][y].setJobHere(true);
			performTask(p);
		}
		else
		{
			for (int dx = 1;dx>=-1;dx--)
			{
				for (int dy = 1;dy>=-1;dy--)
				{
					if (p.map.getNode(dx+x, dy+y)>=0 && !p.main.grid.tiles[x+dx][y+dy].hasJobHere() && (dx != 0 && dy != 0) && !(p.getX() == x && p.getY() == y))
						p.setDestination(x, y);
					else if (p.getX() == x && p.getY() == y && !(dx == 0 && dy == 0))
						p.setDestination(dx+x, dy+y);
				}
			}
		}
	}
	
	@Override
	public void performTask(Person p) 
	{
		p.setHasDestination(false);
		p.setDestination(p.getX(), p.getY());
		if (progress < 20 && !p.main.grid.tiles[x][y].hasPerson())
			progress++;
			p.main.grid.tiles[x][y].setJobHere(true);
		if (progress >= 20 && !p.main.grid.tiles[x][y].hasPerson())
		{
			p.main.grid.setTiles(x, y, type);
			p.finishCurrentTask();
		}
	}
}
